package bll

import (
	"context"
	"fmt"
	"math/rand"
	"maya-service/store/mysql"
	"strings"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type aiQuestion struct {
	iAiQuestion store.IAiQuestion
}

var AiQuestion = &aiQuestion{
	iAiQuestion: mysql.AiQuestion,
}

func init() {
	Register(AiQuestion)
}

func (a *aiQuestion) init() func() {
	return func() {}
}

func (a *aiQuestion) RefreshGuideAnswer() {
	list, err := AiQuestion.List(context.Background(), &model.AiQuestionListRequest{Index: 1, Size: 10000})
	if err != nil {
		return
	}
	for _, v := range list.List {
		if v.ReferenceAnswer == "" {
			continue
		}

		data := []byte(v.ReferenceAnswer)
		value := string(data[0:1])
		if value == "#" || strings.Contains(v.GuideAnswer, "**") {
			continue
		}

		// 生成markdown
		var content, conversationId string
		userId := fmt.Sprintf("%v", rand.Intn(10000))
		conversationId = CreateConversation(userId, "7459732707900850239", "pat_5Do9945xBDp7pBeX7X8DheznuEpm8ijL41aKRp60sbWnJeP2MbmHce2GUZJnyYmu", "")
		content, _, err = SendMessage("7459732707900850239", "pat_5Do9945xBDp7pBeX7X8DheznuEpm8ijL41aKRp60sbWnJeP2MbmHce2GUZJnyYmu", conversationId, userId, v.ReferenceAnswer, nil)
		if content == "" || content == "暂时无法理解你的诉求，请重新组织下语言" {
			continue
		} else {
			_ = AiQuestion.Update(context.Background(), &model.AiQuestionUpdateRequest{
				Id:          v.Id,
				GuideAnswer: &content,
			})
		}

		// ai 优化
		/*conversationId = CreateConversation(userId, "7458183535627780105", "pat_5Do9945xBDp7pBeX7X8DheznuEpm8ijL41aKRp60sbWnJeP2MbmHce2GUZJnyYmu", "")
		content, _, err = SendMessage("7458183535627780105", "pat_5Do9945xBDp7pBeX7X8DheznuEpm8ijL41aKRp60sbWnJeP2MbmHce2GUZJnyYmu", conversationId, userId, content, nil)
		if content != "" {
			_ = AiQuestion.Update(context.Background(), &model.AiQuestionUpdateRequest{
				Id:          v.Id,
				GuideAnswer: &content,
			})
		} else {
			log.Error("#### 生成markdown 文本报错 ", zap.Any("err", err))
		}*/
	}
}

// Create
func (a *aiQuestion) Create(ctx context.Context, in *model.AiQuestionCreateRequest) (int64, error) {
	defer func() {
		a.RefreshGuideAnswer()
	}()
	var (
		err        error
		questionId int64
	)
	c := buildAiQuestion(in)
	questionId, err = a.iAiQuestion.Create(ctx, c)
	return questionId, err
}

// Update
func (a *aiQuestion) Update(ctx context.Context, in *model.AiQuestionUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.Topic != nil {
		dict["topic"] = in.Topic
	}

	if in.Content != nil {
		dict["content"] = in.Content
	}

	if in.Level != nil {
		dict["level"] = in.Level
	}

	if in.Module != nil {
		dict["module"] = in.Module
	}

	if in.ReferenceAnswer != nil {
		dict["reference_answer"] = in.ReferenceAnswer
	}

	if in.Questioner != nil {
		dict["questioner"] = in.Questioner
	}

	if in.Background != nil {
		dict["background"] = in.Background
	}

	if in.GuideAnswer != nil {
		dict["guide_answer"] = in.GuideAnswer
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	if in.Weight != nil {
		dict["weight"] = in.Weight
	}

	/*if in.QuestionerId != nil {
		dict["questioner_id"] = in.QuestionerId
	}*/

	if in.Issue != nil {
		dict["issue"] = in.Issue
	}

	if in.ProductId != nil {
		dict["product_id"] = in.ProductId
	}

	if in.Heat != nil {
		dict["heat"] = in.Heat
	}

	if in.RecommendStrength != nil {
		dict["recommend_strength"] = in.RecommendStrength
	}

	if in.GuideWords != nil {
		dict["guide_words"] = in.GuideWords
	}

	if in.Image != nil {
		dict["image"] = in.Image
	}

	if in.Price != nil {
		dict["price"] = in.Price
	}

	if in.Stock != nil {
		dict["stock"] = in.Stock
	}

	if in.Tag != nil {
		dict["tag"] = in.Tag
	}

	if in.CourseType != nil {
		dict["course_type"] = in.CourseType
	}

	if in.CollectorId != nil {
		dict["collector_id"] = in.CollectorId
	}

	if in.UpDown != nil {
		dict["up_down"] = in.UpDown
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iAiQuestion.Update(ctx, in.Id, dict)
}

// Delete
func (a *aiQuestion) Delete(ctx context.Context, in *model.AiQuestionDeleteRequest) error {
	return a.iAiQuestion.Delete(ctx, in)
}

// List
func (a *aiQuestion) List(ctx context.Context, in *model.AiQuestionListRequest) (*model.AiQuestionListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.AiQuestion
		out   = &model.AiQuestionListResponse{}
	)
	if in.CourseType == nil {
		in.IsFilterOld = true
	}
	if total, list, err = a.iAiQuestion.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.AiQuestionsEntityToDto(list)

	return out, nil
}

// Find
func (a *aiQuestion) Find(ctx context.Context, in *model.AiQuestionInfoRequest) (*model.AiQuestionInfo, error) {
	var (
		err  error
		data *entity.AiQuestion
		out  = &model.AiQuestionInfo{}
	)

	if data, err = a.iAiQuestion.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.AiQuestionEntityToDto(data)
	return out, nil
}

// buildAiQuestion build entity
func buildAiQuestion(in *model.AiQuestionCreateRequest) *entity.AiQuestion {

	ety := &entity.AiQuestion{}

	ety.Topic = in.Topic

	ety.Content = in.Content

	ety.Level = in.Level

	ety.Module = in.Module

	ety.Weight = in.Weight

	ety.ReferenceAnswer = in.ReferenceAnswer

	ety.GuideAnswer = in.ReferenceAnswer
	ety.Background = in.Background
	ety.Questioner = in.Questioner
	//ety.QuestionerId = in.QuestionerId
	ety.GuideWords = in.GuideWords

	ety.Issue = in.Issue
	ety.ProductId = in.ProductId
	ety.Heat = in.Heat
	ety.RecommendStrength = in.RecommendStrength

	ety.CollectorId = in.CollectorId

	ety.Price = in.Price
	ety.Stock = in.Stock

	ety.Tag = in.Tag

	ety.CourseType = in.CourseType

	ety.Image = in.Image

	ety.UpDown = in.UpDown

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
